const toolHelper = require("../utils/toolHelper.js");
const baseUrl = 'http://114.132.85.7:8889';

function api() {
  var api = __wxConfig.envVersion;
  switch (api) {
    case 'develop': // 开发服
      return 'http://114.132.85.7:8889';
      break;
    case 'trial': // 体验服
      return 'http://114.132.85.7:8889';
      break;
    default: // 正式服
      return 'http://114.132.85.7:8889';
  }

}

const header = {
  'Accept': 'application/json',
  'content-type': 'application/json',
  'Authorization': ''
}

function queryData(data) {
  var str = '';
  for (var i in data) {
    str += i + "=" + data[i] + '&';
  }
  if (str) {
    str = '?' + str;
    str = str.substr(0, str.length - 1);
  }
  return str;
}

const http = {};
http.get = function get(url, data, cb) {
  header.Authorization = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''
  wx.request({
    url: api() + url + queryData(data),
    method: 'get',
    header: header,
    success: function (res) {
      let resData = res.data;
      switch (res.statusCode) {
        case 200:
          wx.hideToast();
          toolHelper.isFunction(cb) && cb(resData);
          break;
        case 401:
          wx.showToast({
            icon: "none",
            title: '请重新登录'
          });
          wx.removeStorageSync('token');
          break;
        default:
          wx.hideToast();
          wx.showToast({
            icon: "none",
            title: resData.msg
          });
      }
    },
    fail(res) {
      wx.showModal({
        showCancel: false,
        content: res.msg
      })
    }
  })
}

http.post = function post(url, data, cb) {
  header.Authorization = wx.getStorageSync('token') ? wx.getStorageSync('token') : ''
  wx.request({
    url: api() + url,
    method: 'post',
    data: data,
    header: header,
    success: function (res) {
      let resData = res.data;
      wx.hideToast();
      switch (res.statusCode) {
        case 200:
          toolHelper.isFunction(cb) && cb(resData);
          break;
        case 401:
          wx.showModal({
            title: '错误信息',
            content: resData.msg,
            confirmText: '知道了',
            showCancel: false,
            success(res1) {
              if (res1.confirm) {
                wx.removeStorageSync('token');
              }
            }
          })
          break;
        default:
          wx.showToast({
            icon: "none",
            title: resData.msg
          });
      }
    },
    fail(res) {
      wx.showModal({
        showCancel: false,
        content: res.msg
      })
    }
  });
}


module.exports = http;